import store from '@/store';
import {defineStore} from 'pinia';
import {computed, ref} from 'vue';
import global from '@/utils/global.ts';
import {userStoreOutside} from '@/store/modules/user.ts';
import {getMapperData, MapperData} from '@/components/layout/index.ts';

export const getUserId = (): string => {
  const userStore = userStoreOutside();
  return userStore.getUserId();
};

export const useAppStore: any = defineStore(
  'app',
  () => {
    const mainLoading = ref(false);
    const tabList = ref<MapperData[]>([]);
    const menusPaths = ref<Record<string, MapperData>>({});
    const getKeepCaches = computed(() => {
      return tabList.value.map((item) => item && item.path);
    });

    const setMainLoading = (loading: boolean) => {
      mainLoading.value = loading;
    };
    const setMenusPaths = (paths: Record<string, MapperData>) => {
      menusPaths.value = paths;
      addTab(global.homePage.path);
    };
    const addTab = (path: string) => {
      const list = tabList.value;
      // 判断如果是首页时就不显示关闭按钮
      const tab = getMapperData(menusPaths.value, path);
      if (tab) {
        if (list.length > 0) {
          const _tab = list.find((item) => {
            return item.path === path;
          });
          if (!_tab) {
            tabList.value.push(tab);
          }
        } else {
          tabList.value.push(tab);
        }
      }
    };
    const setTabList = (list) => {
      tabList.value = list;
    };
    const clearCache = () => {
      mainLoading.value = false;
      tabList.value = [];
      menusPaths.value = {};
    };

    return {
      mainLoading: mainLoading,
      keepCaches: getKeepCaches,
      menusPaths: menusPaths,
      tabList: tabList,
      addTab: addTab,
      setTabList: setTabList,
      clearCache: clearCache,
      setMenusPaths: setMenusPaths,
      setMainLoading: setMainLoading
    };
  },
  {
    persist: {
      // 持久化的key名称
      key: (storeId) => `${storeId}:${getUserId()}`,
      // 存储在sessionStorage，默认是存在localStorage中
      storage: window.localStorage,
      serializer: {
        deserialize: JSON.parse,
        serialize: JSON.stringify
      },
      // 要持久化的属性
      paths: ['tabList']
    }
  }
);

// 在组件setup函数外使用
export function appStoreOutside() {
  return useAppStore(store);
}
